
let lifeData = {}

try {
  // 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
  // eslint-disable-next-line no-unused-vars
  lifeData = localStorage.getItem('lifeData')
} catch (e) {

}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
const saveStateKeys = ['app']

// 保存变量到本地存储中
const saveLifeData = function(key, value) {
  // 判断变量名是否在需要存储的数组中
  if (saveStateKeys.includes(key)) {
    // 获取本地存储的lifeData对象，将变量添加到对象中
    let tmp = JSON.parse(localStorage.getItem('lifeData'))
    // 第一次打开APP，不存在lifeData变量，故放一个{}空对象
    tmp = tmp || {}
    tmp[key] = value
    // 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
    localStorage.setItem('lifeData', JSON.stringify(tmp))
  }
}

const getCookieValue = (req, key) => {
  if (!req.headers.cookie) {
    return ''
  }
  const cookies = req.headers.cookie.split(';')
  for (let i = 0; i < cookies.length; i++) {
    const temp = cookies[i].split('=')
    if (temp[0].trim() === key) {
      return temp[1]
    }
  }
  return ''
}

export const state = () => ({})

export const mutations = {
  SET_TOKEN (state, value) {
    state.token = value
  },
  $uStore(state, payload) {
    // 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
    const nameArr = payload.name.split('.')
    let saveKey = ''
    const len = nameArr.length
    if (nameArr.length >= 2) {
      let obj = state[nameArr[0]]
      for (let i = 1; i < len - 1; i++) {
        obj = obj[nameArr[i]]
      }
      obj[nameArr[len - 1]] = payload.value
      saveKey = nameArr[0]
    } else {
      // 单层级变量，在state就是一个普通变量的情况
      state[payload.name] = payload.value
      saveKey = payload.name
    }
    // 保存变量到本地，见顶部函数定义
    saveLifeData(saveKey, state[saveKey])
  }
}

export const actions = {
  async nuxtServerInit ({ dispatch, commit }, { req, params }) {
    const token = getCookieValue(req, 'Admin-Token')
    commit('user/SET_TOKEN', token)
  }
}

export const getters = {
  isLogin: state => state.user.isLogin,
  userId: state => state.user.userId,
  nickName: state => state.user.name,
  username: state => state.user.userName,
}
